# -*- coding: utf-8 -*-
# 标准库导入
import sys
import os

# 第三方库导入
from PyQt5.QtCore import Qt, pyqtSignal, QThread  # 新增QThread导入
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QLineEdit, QPushButton, QTableWidget, QTableWidgetItem,
    QHeaderView, QMessageBox, QStackedWidget, QComboBox, QFormLayout,
    QDialog, QDialogButtonBox, QStyleFactory, QGraphicsDropShadowEffect,
    QSizePolicy, QButtonGroup
)
from PyQt5.QtGui import QFont, QIcon, QPixmap, QColor, QDoubleValidator, QIntValidator
from tqsdk import TqApi, TqAuth, TqAccount, TqSim

# 本地模块导入
from db_manager import (
    connect_db,
    get_all_products,
    insert_product,
    update_product,
    delete_product,
    get_monitored_products,
    delete_product_by_name,
    get_product_by_id
)

# 新增线程类定义
class TqConnectThread(QThread):
    finished = pyqtSignal(object, object, Exception)
    
    def __init__(self, account_info, auth_info):
        super().__init__()
        self.account_info = account_info
        self.auth_info = auth_info

    def run(self):
        try:
            account = TqAccount(*self.account_info)
            api = TqApi(account=account,
                      auth=TqAuth(*self.auth_info),
                      _stock=False)
            acc = api.get_account()
            self.finished.emit(api, acc, None)
        except Exception as e:
            self.finished.emit(None, None, e)

class CapitalManager(QMainWindow):
    update_signal = pyqtSignal(str)
    connection_signal = pyqtSignal(str, bool)
    
    PAGE_INDEX = {
        "CALCULATE": 0,
        "ORDER": 1,
        "PRODUCT_MGMT": 2,
        "AUTO_SL": 3,
        "HELP": 4
    }

    def __init__(self):
        super().__init__()
        self.init_data()
        self.init_ui()
        self.setup_connections()  # 这个调用需要对应下面的方法
        self.setWindowTitle("资金管理系统")
        self.resize(1200, 800)
        self.handle_page_change(0)

    # +++ 添加缺失的UI初始化方法 +++
    def init_ui(self):
        """初始化主界面"""
        main_widget = QWidget()
        main_h_layout = QHBoxLayout(main_widget)
        
        # 侧边栏
        side_panel = self._init_side_panel()
        
        # 主堆叠窗口
        self.stacked_widget = QStackedWidget()
        self.stacked_widget.addWidget(self._init_capital_ui())
        self.stacked_widget.addWidget(self._init_order_ui())
        self.stacked_widget.addWidget(self._init_product_management_ui())
        self.stacked_widget.addWidget(self._init_auto_sl_ui())
        self.stacked_widget.addWidget(self._init_help_ui())
        
        main_h_layout.addWidget(side_panel)
        main_h_layout.addWidget(self.stacked_widget, stretch=1)
        self.setCentralWidget(main_widget)

    # +++ 新增初始化数据方法 +++
    def init_data(self):
        """初始化核心数据"""
        self.products = []  # 从数据库或其他来源加载品种数据
        self.api = None      # 天勤API连接实例
        self.account = None  # 交易账户信息

    def connect_tq(self):
        """连接天勤账户（线程安全版本）"""
        self.connect_btn.setEnabled(False)
        self.connect_btn.setText("连接中...")
        
        # 显示加载状态
        if not hasattr(self, 'loading_label'):
            self.loading_label = QLabel("正在连接天勤账户...", self)
            self.loading_label.setAlignment(Qt.AlignCenter)
            self.loading_label.setStyleSheet("font-size: 14px; color: #666;")
            self.loading_label.hide()
        
        self.loading_label.show()
        
        # 创建并启动线程
        self.thread = TqConnectThread(
            account_info=("H徽商期货", "155831", "alibaba999"),
            auth_info=("szlwy68", "alibaba999")
        )
        self.thread.finished.connect(self._handle_connection_result)
        self.thread.start()

    def _handle_connection_result(self, api, account, error):
        """处理连接结果"""
        self.loading_label.hide()
        self.connect_btn.setEnabled(True)
        self.connect_btn.setText("连接天勤账户")
        
        if error:
            QMessageBox.critical(self, "错误", f"连接失败: {str(error)}")
            return
            
        self.api = api
        self.account = account
        self.capital_input.setText(f"{account.balance:.2f}")
        QMessageBox.information(self, "成功", "账户连接成功")

    # +++ 添加缺失的私有方法 +++
    def _init_side_panel(self):
        """初始化侧边栏"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        buttons = [
            ("资金计算", self.PAGE_INDEX["CALCULATE"]),
            ("订单管理", self.PAGE_INDEX["ORDER"]),
            ("品种管理", self.PAGE_INDEX["PRODUCT_MGMT"]),
            ("自动止损", self.PAGE_INDEX["AUTO_SL"]),
            ("帮助", self.PAGE_INDEX["HELP"])
        ]
        self.btn_group = QButtonGroup()
        for text, idx in buttons:
            btn = QPushButton(text)
            btn.setCheckable(True)
            self.btn_group.addButton(btn, idx)
            layout.addWidget(btn)
        layout.addStretch()
        return panel

    def _init_capital_ui(self):
        """初始化资金计算页面"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 添加资金输入框和连接按钮
        form = QFormLayout()
        self.capital_input = QLineEdit()
        self.capital_input.setPlaceholderText("点击连接账户自动获取")
        self.capital_input.setReadOnly(True)
        
        self.connect_btn = QPushButton("连接天勤账户")
        self.connect_btn.setStyleSheet("background-color: #4CAF50; color: white;")
        
        form.addRow("账户资金:", self.capital_input)
        form.addRow(self.connect_btn)
        
        layout.addLayout(form)
        layout.addStretch()
        return widget

    def _init_order_ui(self):
        """初始化订单管理页面"""
        return QWidget()  # 暂留空实现

    def _init_product_management_ui(self):
        """初始化品种管理页面"""
        return QWidget()  # 暂留空实现

    def _init_auto_sl_ui(self):
        """初始化自动止损页面"""
        return QWidget()  # 暂留空实现

    def _init_help_ui(self):
        """初始化帮助页面"""
        return QWidget()  # 暂留空实现

    # +++ 删除重复的connect_tq和_handle_connection_result方法 +++
    # 保留唯一的connect_tq和_handle_connection_result实现

    # +++ 新增信号连接方法 +++
    def setup_connections(self):
        """连接所有信号与槽"""
        # 侧边栏按钮点击事件
        self.btn_group.buttonClicked.connect(self.handle_page_change)
        # 连接天勤账户按钮
        self.connect_btn.clicked.connect(self.connect_tq)

    def handle_page_change(self, index):
        """处理页面切换"""
        self.stacked_widget.setCurrentIndex(index)
        # 更新按钮选中状态
        for btn in self.btn_group.buttons():
            btn.setChecked(self.btn_group.id(btn) == index)

if __name__ == "__main__":
    os.environ["QT_LOGGING_RULES"] = "qt.png.warning=false"
    
    app = QApplication(sys.argv)
    app.setStyle(QStyleFactory.create("WindowsVista")) 
    app.setFont(QFont("微软雅黑", 9))
    app.setStyleSheet("""
        * {
            font-family: "微软雅黑", "Consolas";
            font-size: 10pt;
        }
        QTableWidget {
            background-color: white;
            border: 1px solid #E0E0E0;
            margin-top: 10px;
        }
        QLineEdit, QTableWidget, QLabel {
            min-height: 25px;
            padding: 2px 5px;
        }
        QTableWidget {
            min-width: 800px;
        }
        QLineEdit {
            min-width: 150px;
        }
        QComboBox {
            min-width: 200px;
        }
    """)
    app.setWindowIcon(QIcon('app.png'))
    window = CapitalManager()
    window.show()
    sys.exit(app.exec_())
